package com.chezhujie.www.controller;

import com.chezhujie.www.domain.Shop;
import com.chezhujie.www.service.ShopService;
import com.xy.core.page.Pagination;
import com.xy.core.utils.ConvertObj;
import com.xy.core.utils.Fileupload;
import com.xy.core.utils.UUIDUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *   店铺信息
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    private ShopService shopService;

    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, Shop shop, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(shop,req,model);
        setClassify(model);
        setClassType(model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(shop);
            Pagination pagination = shopService.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取店铺信息列表失败!"+e.getMessage());
        }
        model.addAttribute("entity", shop);
        return "shop/list";
    }
    /** 保存 **/
    @RequestMapping("/save.do")
    public String save(Shop shop,
            @RequestParam(value = "filePicPath", required = false) MultipartFile multipartFile_PicPath,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(shop.getShopId())){
                String picPath = shop.getPicPath();
                setPicPath(shop,multipartFile_PicPath,req);
                shopService.update(shop);
                Fileupload.deleteFile(req,picPath);


            }else{
                shop.setShopId(UUIDUtils.getUUID());
                setPicPath(shop,multipartFile_PicPath,req);
                shopService.insert(shop);
            }
            model.addAttribute("success", "保存店铺信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存店铺信息失败!详情："+e.getMessage());
        }
        return "redirect:list.do";
    }
    private void setPicPath(Shop shop, MultipartFile multipartFile, HttpServletRequest req) throws Exception {
        if((!multipartFile.isEmpty())&&multipartFile.getSize()>0){
            String basePath = req.getSession().getServletContext().getRealPath("/");
            String path = basePath+"upload/shop/"+shop.getShopId()+"-"+ System.currentTimeMillis()+multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            Fileupload.createDir(basePath+"upload/shop/");

            InputStream in = multipartFile.getInputStream();
            FileOutputStream out = new FileOutputStream(path);
            try {
                IOUtils.copy(in,out);
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("上传图片失败！");
            }finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
            }

            String picPath = "/"+path.replace(basePath, "");
            shop.setPicPath(picPath);
        }
    }


    /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)String shopId,Shop shop, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(shop,req,model);
        setClassify(model);
        setClassType(model);
        try {
            Shop entity = shopService.queryById(shop.getShopId());
            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询店铺信息出错!详情："+e.getMessage());
        }
        return "shop/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(Shop shop, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(shop,req,model);
        setClassify(model);
        setClassType(model);
        if(StringUtils.isNotBlank(shop.getShopId())){
            shop = shopService.queryById(shop.getShopId());
            model.addAttribute("entity", shop);
        }
        return "shop/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)String shopId,Shop shop, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            shopService.deleteById(shop.getShopId());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }
    private void setClassify(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listClassify = shopService.getListClassify(param);
        // map.put("name","");
        // map.put("value","");
        model.addAttribute("listClassify", listClassify);
    }
    private void setClassType(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listClassType = shopService.getListClassType(param);
        // map.put("name","");
        // map.put("value","");
        model.addAttribute("listClassType", listClassType);
    }

    private void setMsg(Shop shop,HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", shop);
    }
}
